package com.ly.lypopupwindowdemo.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;

import com.ly.lypopupwindowdemo.MyApplication;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;

/**
 * Created by Yhyu on 2015/5/29.
 */
public class FileUtil {
    /**
     * 创建文件夹
     *
     * @param dir
     */
    public static void mkDirs(String dir) {
        if (TextUtils.isEmpty(dir))
            return;
        File file = new File(dir);
        if (!file.exists())
            file.mkdirs();
        if (file.isFile()) {
            file.delete();
            file.mkdirs();
        }
    }

    /**
     * 格式化输出文件大小，0.22M
     *
     * @param size
     * @return
     */
    public static String formatFileSize(double size) {
        DecimalFormat decimalFormat = new DecimalFormat("#0.00");
        String result = "0.00B";

        int count;
        for (count = 0; size > 1024.0D; size /= 1024.0D) {
            ++count;
        }
        switch (count) {
            case 0:
                result = decimalFormat.format(size) + "B";
                break;
            case 1:
                result = decimalFormat.format(size) + "K";
                break;
            case 2:
                result = decimalFormat.format(size) + "M";
                break;
            case 3:
                result = decimalFormat.format(size) + "G";
        }
        return result;
    }

    /**
     * 递归获取文件夹或文件的大小
     *
     * @param dir
     * @return 返回字节
     */
    public static double getFileSize(File dir) {
        //判断文件是否存在
        if (dir.exists()) {
            //如果是目录则递归计算其内容的总大小
            if (dir.isDirectory()) {
                File[] children = dir.listFiles();
                double size = 0;
                for (File f : children)
                    size += getFileSize(f);
                return size;
            } else {
                double size = (double) dir.length();
                return size;
            }
        } else {
            System.out.println("文件或者文件夹不存在，请检查路径是否正确！");
            return 0.0;
        }
    }

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     *
     * @param dir 将要删除的文件目录
     * @return boolean Returns "true" if all deletions were successful.
     * If a deletion fails, the method stops attempting to
     * delete and returns "false".
     */

    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }

    /**
     * 生成一个图片文件名
     *
     * @return
     */
    public static String generateImagename() {
        return "temp_" + System.currentTimeMillis() + ".jpg";
    }

    public static String generateVoiceName() {
        return "temp_" + System.currentTimeMillis() + "voice.map";
    }

    public static void saveFile(final Bitmap bm, File file) {
        OutputStream outStream = null;
        ByteArrayOutputStream baos = null;
        try {
            /*
             * if(bm.isRecycled()){ return; }
			 */
            baos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
            byte[] data = baos.toByteArray();

            outStream = new FileOutputStream(file);
            outStream.write(data, 0, data.length);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeStream(outStream);
            closeStream(baos);
        }
    }

    private static void closeStream(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static Drawable getStartPageDrawable(String path) {
        File file = new File(path);
        if (file.exists()) {
            try {
                Bitmap bt = BitmapFactory.decodeFile(path);
                return new BitmapDrawable(bt);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * @param ASSETS_NAME 要复制的文件名
     * @param savePath    要保存的路径
     */

    public static void copyAssetsFile(String ASSETS_NAME, String savePath) {
        String filename = savePath + "/" + ASSETS_NAME;

        File dir = new File(savePath);
        // 如果目录不中存在，创建这个目录
        if (!dir.exists())
            dir.mkdir();
        try {
            if (!(new File(filename)).exists()) {
                InputStream is = MyApplication.getInstance().getResources().getAssets()
                        .open(ASSETS_NAME);
                FileOutputStream fos = new FileOutputStream(filename);
                byte[] buffer = new byte[7168];
                int count = 0;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                fos.close();
                is.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    /**
     * 小于1M 以KB返回, 否则以MB返回
     *
     * @param size
     * @return
     */
    public static String formatMB(long size) {
        DecimalFormat df = new DecimalFormat("###.##");
        float f;
        if (size < 1024 * 1024) {
            f = (float) ((float) size / (float) 1024);
            return (df.format(new Float(f).doubleValue()) + "KB");
        } else {
            f = (float) ((float) size / (float) (1024 * 1024));
            return (df.format(new Float(f).doubleValue()) + "MB");
        }
    }


}
